import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/user';

// 创建axios实例
const request = axios.create({
  baseURL: import.meta.env.DEV ? '/api' : 'http://localhost:8080/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 对于Spring Boot后端，直接返回data
    return { data: response.data, message: 'success' };
  },
  (error) => {
    console.error('响应错误:', error);
    
    if (error.response) {
      const { status, data } = error.response;
      let message = '请求失败';
      
      switch (status) {
        case 400:
          message = data.message || '请求参数错误';
          break;
        case 401:
          message = '登录已过期，请重新登录';
          const userStore = useUserStore();
          userStore.logout();
          window.location.href = '/login';
          break;
        case 403:
          message = '权限不足';
          break;
        case 404:
          message = '请求的资源不存在';
          break;
        case 500:
          message = '服务器内部错误';
          break;
        default:
          message = data.message || '网络错误';
      }
      
      ElMessage.error(message);
    } else if (error.request) {
      ElMessage.error('网络连接失败，请检查网络');
    } else {
      ElMessage.error('请求配置错误');
    }
    
    return Promise.reject(error);
  }
);

// 认证相关API
export const authApi = {
  // 登录 - 对接Spring Boot的/api/auth/login
  login: (data) => {
    const loginData = {
      username: data.username,
      password: data.password
    };
    return request.post('/auth/login', loginData);
  },
  
  // 注册 - 对接Spring Boot的/api/auth/register
  register: (data) => {
    const registerData = {
      username: data.username,
      email: data.email,
      password: data.password,
      mobile: data.mobile || data.phone
    };
    return request.post('/auth/register', registerData);
  },
  
  // 登出
  logout: () => {
    return Promise.resolve({ data: { message: 'Logged out successfully' } });
  },
  
  // 获取用户信息 - 对接Spring Boot的/api/auth/me
  getUserInfo: () => {
    return request.get('/auth/me')
  },
  
  // 检查用户名可用性
  checkUsernameAvailable: (username) => {
    return request.get(`/auth/check-username?username=${username}`);
  },

  // 发送短信验证码 (注册用)
  sendSmsCode: (phone, type = 'register') => {
    return request.post('/auth/sms-code', { phone, type });
  },

  // 验证码登录
  loginWithCode: (data) => {
    return request.post('/auth/login-code', data);
  },

  // 重置密码
  resetPassword: (data) => {
    return request.post('/auth/reset-password', data);
  },

  // 验证重置密码验证码
  verifyResetCode: (data) => {
    return request.post('/auth/verify-reset-code', data);
  }
};

// 洗护订单相关API - 对接Spring Boot的/api/laundry
export const orderApi = {
  // 创建订单 - 对接/api/laundry/orders
  createOrder: (data) => {
    // 转换前端订单数据到后端格式
    const orderData = {
      customerName: data.customerName,
      customerPhone: data.customerPhone,
      pickupAddress: data.pickupAddress,
      deliveryAddress: data.deliveryAddress,
      totalAmount: data.totalAmount,
      items: data.items || [],
      status: data.status || 'PENDING'
    };
    return request.post('/laundry/orders', orderData);
  },
  
  // 获取订单列表 - 对接/api/laundry/orders
  getOrderList: (params) => {
    // 处理查询参数
    return request.get('/laundry/orders', { params });
  },
  
  // 获取订单详情 - 对接/api/laundry/orders/{id}
  getOrderDetail: (id) => request.get(`/laundry/orders/${id}`),
  
  // 更新订单 - 对接/api/laundry/orders/{id}
  updateOrder: (id, data) => {
    return request.put(`/laundry/orders/${id}`, data);
  },
  
  // 取消订单
  cancelOrder: (id, reason) => {
    // 通过更新订单状态来取消
    return request.put(`/laundry/orders/${id}`, { 
      status: 'CANCELLED',
      cancelReason: reason 
    });
  },
  
  // 确认订单
  confirmOrder: (id) => {
    return request.put(`/laundry/orders/${id}`, { status: 'CONFIRMED' });
  },
  
  // 删除订单 - 对接/api/laundry/orders/{id}
  deleteOrder: (id) => request.delete(`/laundry/orders/${id}`),
  
  // 评价订单 - 可能需要额外的后端端点
  rateOrder: (id, data) => {
    return request.post(`/laundry/orders/${id}/rating`, data);
  },
  
  // 获取订单进度 - 可能需要额外的后端端点
  getOrderProgress: (id) => {
    return request.get(`/laundry/orders/${id}/progress`);
  },
  
  // 获取订单统计 - 可能需要额外的后端端点
  getOrderStats: () => {
    return request.get('/laundry/orders/stats');
  },
  
  // 重新下单
  reorder: (id) => {
    return request.post(`/laundry/orders/${id}/reorder`);
  }
};

// 商家管理API - 对接Spring Boot的/api/merchants
export const merchantApi = {
  // 获取商家列表 - 对接/api/merchants
  getMerchantList: (params) => request.get('/merchants', { params }),

  // 获取商家详情 - 对接/api/merchants/{id}
  getMerchantDetail: (id) => request.get(`/merchants/${id}`),

  // 获取商家服务 - 对接/api/merchants/{id}/services
  getMerchantServices: (id, params) => request.get(`/merchants/${id}/services`, { params }),

  // 获取高评分商家 - 对接/api/merchants/top-rated
  getTopRatedMerchants: (params) => request.get('/merchants/top-rated', { params }),

  // 获取热门商家 - 对接/api/merchants/popular
  getPopularMerchants: (params) => request.get('/merchants/popular', { params })
};

// 服务管理API - 对接Spring Boot的/api/services
export const serviceApi = {
  // 获取服务分类 - 对接/api/services/categories
  getServiceCategories: () => request.get('/services/categories'),

  // 获取服务列表 - 对接/api/services
  getServiceList: (params) => request.get('/services', { params }),

  // 获取服务详情 - 对接/api/services/{id}
  getServiceDetail: (id) => request.get(`/services/${id}`),

  // 获取推荐服务 - 对接/api/services/recommended
  getRecommendedServices: (params) => request.get('/services/recommended', { params }),

  // 获取热门服务 - 对接/api/services/hot
  getHotServices: (params) => request.get('/services/hot', { params }),

  // 搜索服务 - 对接/api/services/search
  searchServices: (params) => request.get('/services/search', { params })
};

// 搜索功能API - 对接Spring Boot的/api/search
export const searchApi = {
  // 综合搜索 - 对接/api/search
  search: (params) => request.get('/search', { params }),

  // 搜索服务 - 对接/api/search/services
  searchServices: (params) => request.get('/search/services', { params }),

  // 搜索商家 - 对接/api/search/merchants
  searchMerchants: (params) => request.get('/search/merchants', { params }),

  // 获取推荐内容 - 对接/api/search/recommendations
  getRecommendations: () => request.get('/search/recommendations')
};

// 仪表板API - 对接Spring Boot的/api/dashboard
export const dashboardApi = {
  // 获取用户仪表板 - 对接/api/dashboard
  getUserDashboard: () => request.get('/dashboard'),

  // 获取订单统计 - 对接/api/dashboard/orders/stats
  getOrderStats: () => request.get('/dashboard/orders/stats')
};

// 用户管理API - 对接Spring Boot的/api/user
export const userApi = {
  // 获取用户资料 - 对接/api/user/profile
  getUserProfile: () => request.get('/user/profile'),

  // 更新用户资料 - 对接/api/user/profile
  updateUserProfile: (data) => request.put('/user/profile', data),

  // 修改密码 - 对接/api/user/change-password
  changePassword: (data) => request.put('/user/change-password', data),

  // 更新手机号 - 对接/api/user/mobile
  updateMobile: (data) => request.put('/user/mobile', data),

  // 更新邮箱 - 对接/api/user/email
  updateEmail: (data) => request.put('/user/email', data),

  // 实名认证 - 对接/api/user/verify-real-name
  verifyRealName: (data) => request.post('/user/verify-real-name', data)
};

// 地址管理API - 对接Spring Boot的/api/user/addresses
export const addressApi = {
  // 获取地址列表 - 对接/api/user/addresses
  getAddressList: () => request.get('/user/addresses'),

  // 添加地址 - 对接/api/user/addresses
  addAddress: (data) => request.post('/user/addresses', data),

  // 获取地址详情 - 对接/api/user/addresses/{id}
  getAddressDetail: (id) => request.get(`/user/addresses/${id}`),

  // 更新地址 - 对接/api/user/addresses/{id}
  updateAddress: (id, data) => request.put(`/user/addresses/${id}`, data),

  // 删除地址 - 对接/api/user/addresses/{id}
  deleteAddress: (id) => request.delete(`/user/addresses/${id}`),

  // 设置默认地址 - 对接/api/user/addresses/{id}/default
  setDefaultAddress: (id) => request.put(`/user/addresses/${id}/default`)
};

// 文件上传API - 对接Spring Boot的/api/upload
export const uploadApi = {
  // 上传单个文件 - 对接/api/upload
  uploadFile: (file, type = 'image') => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);

    return request.post('/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 上传多个文件 - 对接/api/upload/multiple
  uploadFiles: (files, type = 'image') => {
    const formData = new FormData();
    files.forEach(file => {
      formData.append('files', file);
    });
    formData.append('type', type);

    return request.post('/upload/multiple', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
};

export default request;